#ifndef ESP_MQTT_IMPL_H
#define ESP_MQTT_IMPL_H

#include "mqtt.h"
#include "mqtt_client.h" // For esp_mqtt_client_handle_t and esp_mqtt_event_handle_t
#include "freertos/FreeRTOS.h" // Required for EventGroupHandle_t
#include "freertos/event_groups.h" // Required for EventGroupHandle_t
#include <string>
#include <memory> // For std::unique_ptr (though client_bridge_ is removed, kept for now if other unique_ptrs are used)

class EspMqttImpl : public Mqtt {
public:
    EspMqttImpl();
    virtual ~EspMqttImpl();

    bool Connect(const std::string broker_address, int broker_port, const std::string client_id, const std::string username, const std::string password) override;
    void Disconnect() override;
    bool Publish(const std::string topic, const std::string payload, int qos = 0) override;
    bool Subscribe(const std::string topic, int qos = 0) override;
    bool Unsubscribe(const std::string topic) override;
    bool IsConnected() override;

private:
    static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data);
    void internal_event_handler(esp_event_base_t base, int32_t event_id, void *event_data); // Renamed from MqttEventCallback for clarity

    // Event handlers called by internal_event_handler
    void handle_connected(esp_mqtt_event_handle_t const event);
    void handle_disconnected(esp_mqtt_event_handle_t const event);
    void handle_data(esp_mqtt_event_handle_t const event);
    void handle_subscribed(esp_mqtt_event_handle_t event);
    void handle_unsubscribed(esp_mqtt_event_handle_t event);
    void handle_published(esp_mqtt_event_handle_t event);
    void handle_error(esp_mqtt_event_handle_t event);

    esp_mqtt_client_handle_t mqtt_client_handle_ = nullptr;
    EventGroupHandle_t mqtt_event_group_ = nullptr;
    
    bool is_connected_ = false;
};

#endif // ESP_MQTT_IMPL_H